package com.example.videotest;

import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.MediaController;
import android.widget.VideoView;

import androidx.appcompat.app.AppCompatActivity;

import com.squareup.picasso.Picasso;

public class FileShowActivity extends AppCompatActivity {

    private static final String TAG = "FileShowActivity";
    private static final int SERVER_PORT = 8087;
    private static final int SINGLE_IMAGE_DISPLAY_DURATION = 10000; // 每次图片展示的时间：10秒

    private VideoView videoView;
    private ImageView imageView;
    private NotificationServer notificationServer;
    private static boolean isServerRunning = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_file_show);

        videoView = findViewById(R.id.videoView);
        imageView = findViewById(R.id.imageView);
        MediaController mediaController = new MediaController(this);
        mediaController.setAnchorView(videoView);
        videoView.setMediaController(mediaController);

        // 启动 NotificationServer
        if (!isServerRunning) {
            notificationServer = new NotificationServer(SERVER_PORT, this);
            notificationServer.startServer();
            isServerRunning = true;
        }

        String url = getIntent().getStringExtra("FILE_URL");
        int playCount = getIntent().getIntExtra("PLAY_COUNT", 1); // 默认播放一次

        if (url != null && !url.isEmpty()) {
            if (isImageUrl(url)) {
                showImage(url,  playCount);
            } else {
                playVideo(url, playCount);
            }
        } else {
            Log.e(TAG, "File URL is null or empty.");
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (notificationServer != null) {
            notificationServer.stopServer();
            isServerRunning = false;
        }
    }

    private boolean isImageUrl(String url) {
        String lowerUrl = url.toLowerCase();
        return lowerUrl.endsWith(".jpg") || lowerUrl.endsWith(".jpeg") || lowerUrl.endsWith(".png") || lowerUrl.endsWith(".gif");
    }

    private void showImage(String imageUrl, int playCount) {
        Log.e(TAG, "展示的图片url为: " + imageUrl);
        Log.e(TAG, "展示时间为: " + playCount * 10 + "s");

        imageView.setVisibility(View.VISIBLE);
        videoView.setVisibility(View.GONE);

        Picasso.get().load(imageUrl).into(imageView);

        imageView.postDelayed(() -> {
            Log.d(TAG, "Image display completed.");
            finish();
        }, SINGLE_IMAGE_DISPLAY_DURATION * playCount);
    }

    private void playVideo(String videoUrl, int playCount) {
        Log.e(TAG, "视频播放url为: " + videoUrl);
        Log.e(TAG, "剩余播放次数为: " + playCount);

        // 将传入的视频URL字符串解析为一个Uri对象
        Uri videoUri = Uri.parse(videoUrl);
        // 设置 VideoView 的视频源为解析后的 Uri
        videoView.setVideoURI(videoUri);

        videoView.setVisibility(View.VISIBLE);
        imageView.setVisibility(View.GONE);

        // 设置一个监听器，在视频准备好播放时自动开始播放
        videoView.setOnPreparedListener(mp -> videoView.start());

        // 设置一个错误监听器，在播放过程中出现错误时进行处理
        videoView.setOnErrorListener((mp, what, extra) -> {
            Log.e(TAG, "Error occurred while playing video. What: " + what + " Extra: " + extra);
            return true;
        });

        // 设置一个播放完成监听器，在视频播放完毕时执行特定操作
        videoView.setOnCompletionListener(mp -> {
            Log.d(TAG, "Video playback completed.");
            if (playCount > 1) {
                playVideo(videoUrl, playCount - 1);
            }
        });
    }
}